'use strict';

const createConfig = require('uni-config-center');
const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class IntegralController extends Controller {
	// 添加商品
	async add() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let {
			goods
		} = this.ctx.data;

		goods.name = goods.name ? goods.name + '' : '';
		goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

		// 是否填写商品分享设置
		goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
		goods.share_img = goods.share_img || goods.img;
		goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

		// 商品默认值
		const goods_id = new Date().getTime() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0');
		goods._id = goods_id;
		goods.stock_wh_num = goods.stock_num;
		goods.create_time = new Date().getTime();
		goods.create_uid = this.ctx.auth.uid;
		goods.create_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;
		// 写入商品数据
		const goodsRes = await this.db.collection('usemall-integral-goods').add(goods);

		response.code = 0;
		response.msg = '提交成功';

		return response;
	}
	// 验证请求数据
	validate(req) {
		if (!req) this.throw('请求参数不存在');
		if (!req.goods) this.throw('商品参数不存在');

		if (!req.goods.name) this.throw('商品名称必填');
		if (!req.goods.cid) this.throw('请选择商品分类');
		if (req.goods.integral <= 0) this.throw('商城积分不能小于0');
		if (!req.goods.img) this.throw('请上传商品主图');
	}

	// 获取商品数据
	async detail() {
		let response = {
			code: 1,
			goods: {},
			goods_detail: {},
		};

		let start = new Date().getTime();
		const {
			goods_id
		} = this.ctx.data;

		// 产品数据
		let goods = await this.db.collection('usemall-integral-goods').doc(goods_id).get();

		if (!goods || goods.data.length <= 0) {
			response.msg = `当前产品不存在`;
			return response;
		}

		response.goods = goods.data[0];

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 编辑商品
	async edit() {
		let response = {
			code: 1,
		};

		// 数据验证
		this.validate(this.ctx.data);

		let {
			goods_id,
			goods
		} = this.ctx.data;
		try {

			// 产品数据
			let __goods = await this.db.collection('usemall-integral-goods').doc(goods_id).get();

			if (!__goods || __goods.data.length <= 0) {
				response.msg = `当前产品不存在`;
				return response;
			}

			goods.name = goods.name ? goods.name + '' : '';
			goods.name_pw = goods.name_pw ? goods.name_pw + '' : '';

			// 是否填写商品分享设置
			goods.share_title = goods.share_title ? goods.share_title + '' : goods.name;
			goods.share_img = goods.share_img || goods.img;
			goods.share_desc = goods.share_desc ? goods.share_desc + '' : goods.name_pw;

			// 商品默认值
			goods.last_modify_uname = new Date().getTime();
			goods.last_modify_uid = this.ctx.auth.uid;
			goods.last_modify_uname = this.ctx.auth.userInfo.username || this.ctx.auth.userInfo.nickname;

			delete goods._id;
			// 写入商品数据
			const goodsRes = await this.db.collection('usemall-integral-goods').doc(goods_id).update(goods);

			response.code = 0;
			response.msg = '提交成功';

		} catch (e) {
			//TODO handle the exception
			console.log('catch', e);
		}
		return response;
	}

	// 导入数据
	async import() {
		let response = {
			code: 1,
		};

		let {
			goodsDatas
		} = this.ctx.data;

		let ids = [];
		let addGoods = [];
		goodsDatas.forEach(x => {
			addGoods.push({
				cid: x.cid,
				cids: [x.cid],
				sort: x.sort,
				name: x.name,
				name_pw: x.name_pw,
				integral: x.price,
				price: x.market_price,
				limit: x.limit,
				stock_num: x.stock_num,
				exchange_cnt: 0,
				exchange: 0,
				visit_cnt: 0,
				visit: 0,
				collect_cnt: 0,
				collect: 0,
				share_cnt: 0,
				share: 0,
				state: x.state,
				img: x.img,
				imgs: x.imgs,
				desc_mobile: x.desc_mobile,
				share_title: x.share_title,
				share_img: x.share_img,
				share_desc: x.share_desc,
				import_id: x._id
			})
			ids.push(x._id);
		});

		// todo 验证导入数据不能重复
		let exitsRes = await this.db.collection('usemall-integral-goods').where({
			import_id: this.db.command.in(ids)
		}).get();

		if (exitsRes.data && exitsRes.data.length > 0) {
			response.msg = '导入的商品数据已存在，请重新操作';
			return response;
		}

		// 写入商品数据
		const goodsRes = await this.db.collection('usemall-integral-goods').add(addGoods);

		response.code = 0;
		response.msg = '导入成功';
		response.datas = goodsRes;

		return response;
	}
	
	// 订单列表
	async orderList() {
		const response = {
			code: 1,
			total: 0,
			datas: []
		};
	
		let {
			page,
			rows,
			group,
			orderby,
			state,
			order_id,
			order_member_name,
			order_member_mobile,
			order_consignee,
			order_consignee_tel,
			begin_time,
			end_time
		} = this.ctx.data;
	
		const whereObj = {
			is_delete: 0
		};
	
		// 状态
		if (state != '全部') {
			whereObj.state = state;
		}
	
		// 订单ID
		if (order_id) {
			whereObj.order_id = new RegExp(this.service.utils.filterRegexpKey(order_id), 'i');
		}
		// 下单人
		if (order_member_name) {
			whereObj.order_member_name = new RegExp(this.service.utils.filterRegexpKey(order_member_name), 'i');
		}
		// 下单人手机号
		if (order_member_mobile) {
			whereObj.order_member_mobile = new RegExp(this.service.utils.filterRegexpKey(order_member_mobile),
				'i');
		}
		// 收货人
		if (order_consignee) {
			whereObj.order_consignee = new RegExp(this.service.utils.filterRegexpKey(order_consignee), 'i');
		}
		// 收货人手机号
		if (order_consignee_tel) {
			whereObj.order_consignee_tel = new RegExp(this.service.utils.filterRegexpKey(order_consignee_tel),
				'i');
		}
		// 下单时间
		if (begin_time && end_time) {
			whereObj.create_time = dbcmd.gte(begin_time).and(dbcmd.lte(end_time));
		}
	
		// 分组状态数量
		let groupWhereObj = Object.assign({}, whereObj);
		delete groupWhereObj[group.field];
	
		const groupRes = await this.db.collection('usemall-integral-order')
			.aggregate()
			.match(groupWhereObj)
			.group({
				_id: '$' + group.field,
				cnt: $.sum(1)
			})
			.end();
	
		if (groupRes && groupRes.data) {
			response.groupDatas = groupRes.data;
			group.datas = [];
			group.total = 0;
	
			for (let key in group.obj) {
				group.obj[key] = 0;
			}
	
			response.groupDatas.forEach(x => {
				if (Object.keys(group.obj).includes(x._id + "")) {
					group.obj[x._id] = x.cnt;
					group.total += x.cnt;
				}
			})
			if (Object.keys(group.obj).includes('全部')) {
				group.obj['全部'] = group.total;
			}
	
			for (let key in group.obj) {
				group.datas.push({
					name: key,
					cnt: group.obj[key]
				})
			}
			response.group = group;
		}
	
		// 总数
		const countRes = await this.db.collection('usemall-integral-order').where(whereObj).count();
		response.total = countRes.total;
	
		// 排序
		orderby = orderby.split(' ');
	
		const res = await this.db.collection('usemall-integral-order')
			.where(whereObj)
			.orderBy(orderby[0], orderby[1])
			.field({
				order_id: true,
				order_member_headimg: true,
				order_member_name: true,
				order_total_money: true,
				order_actural_paid: true,
				order_type: true,
				state: true,
				order_member_mobile: true,
				order_pay_way: true,
				order_consignee: true,
				order_consignee_tel: true,
				order_from: true,
				last_modify_time: true,
				create_time: true
			})
			.skip((page - 1) * rows)
			.limit(rows)
			.get();
	
		// 判断环境
		const isDevelopment = uidConfig.config('env') === 'dev';
	
		res.data.forEach(x => {
			// 测试环境下 进行脱敏处理
			if (isDevelopment) {
				x.order_member_mobile = this.service.utils.desz(x.order_member_mobile);
				x.order_consignee = this.service.utils.desz(x.order_consignee);
				x.order_consignee_tel = this.service.utils.desz(x.order_consignee_tel);
			}
		});
	
		response.code = 0;
		response.datas = res.data;
		return response;
	}
	
	// 订单详情
	async orderDetail() {
		const response = {
			code: 1,
			total: 0,
			datas: {}
		};
	
		const {
			id
		} = this.ctx.data;
	
		const whereObj = {
			order_id: id
		};
	
		const orderLogRes = await this.db.collection('usemall-order-log')
			.where(whereObj)
			.orderBy('create_time', 'asc')
			.field({
				log_type: true,
				create_time: true
			})
			.limit(30)
			.get();
	
		const integralOrderRes = await this.db.collection('usemall-integral-order')
			.where(whereObj)
			.field({
				order_id: true,
				order_member_openid: true,
				order_member_headimg: true,
				order_member_name: true,
				order_member_mobile: true,
				order_consignee: true,
				order_consignee_addr: true,
				order_consignee_addr_detail: true,
				order_consignee_tel: true,
				order_type: true,
				order_express: true,
				order_express_no: true,
				order_pay_no: true,
				order_pay_way: true,
				order_pay_original: true,
				order_pay_state: true,
				order_total_money: true,
				order_total_cnt: true,
				order_way: true,
				order_info: true,
				order_goods_cnt: true,
				order_actural_paid: true,
				order_from: true,
				state: true,
				remark: true
			})
			.get();
	
		const [integralOrder] = integralOrderRes.data;
	
		const isDevelopment = uidConfig.config('env') === 'dev';
	
		// 测试环境下 进行脱敏处理
		if (isDevelopment) {
			integralOrder.order_member_mobile = this.service.utils.desz(integralOrder.order_member_mobile);
			integralOrder.order_consignee = this.service.utils.desz(integralOrder.order_consignee);
			integralOrder.order_consignee_tel = this.service.utils.desz(integralOrder.order_consignee_tel);
		}
	
		response.code = 0;
		response.datas.logs = orderLogRes.data;
		response.datas.order = integralOrder;
		return response;
	}
	
	// 发货
	async orderDelivery() {
		let response = {
			code: 1,
		};
	
		const {
			id,
			expressForm
		} = this.ctx.data;
	
		const uid = this.ctx.auth.uid;
	
		const integralOrderRes = await this.db.collection('usemall-integral-order').doc(id).get();
		const [integralOrder] = integralOrderRes.data;
	
		if (!(integralOrder && integralOrder._id)) {
			response.msg = `此发货订单不存在`;
			return response;
		}
	
		let express = '';
		if (expressForm.order_type == '发货订单') {
			const expressRes = await this.db.collection('usemall-order-express').doc(expressForm.express_id)
				.field({
					name: true,
					encoding: true,
					wx_encoding: true
				}).get();
			[express] = expressRes.data;
		}
	
		// 修改订单数据
		await this.db.collection('usemall-integral-order').doc(id).update({
			order_type: expressForm.order_type,
			order_express: express.name,
			order_express_com: express.encoding,
			order_wx_express_com: express.wx_encoding,
			order_express_no: expressForm.express_no,
			state: expressForm.state,
			deliver_time: Date.now(),
			last_modify_uid: uid,
			last_modify_uname: this.ctx.auth.userInfo.username,
			last_modify_time: Date.now()
		});
	
		// 判断是 实物订单 还是 虚拟订单
		let remark = '快递公司：' + express.name + '<br/>' +
			' 快递单号：' + expressForm.express_no;
	
		if (expressForm.order_type == '虚拟订单') {
			remark = '虚拟订单，确认发货';
		}
	
		// 添加订单日志
		await this.db.collection('usemall-order-log').add({
			order_id: integralOrder.order_id,
			log_type: '商家发货',
			current_state: '待收货',
			prev_state: '待发货',
			remark: remark,
			ip: this.ctx.context.CLIENTIP,
			create_uid: uid,
			create_time: Date.now(),
			create_uname: this.ctx.auth.userInfo.username
		});
	
		response.code = 0;
		response.msg = '发货成功';
		return response;
	}
	
	// 已收货
	async orderReceived() {
		let response = {
			code: 1
		};

		const start = new Date().getTime();
		const nowdate = start;

		const {
			order_id,
			state
		} = this.ctx.data;
		
		const uid = this.ctx.auth.uid;

		let where_obj = {
			is_delete: 0,
			order_id: order_id
		};

		let orderRes = await this.db.collection('usemall-integral-order')
			.where(where_obj)
			.field({
				order_actural_paid: true,
				order_id: true,
				order_member_name: true,
				order_member_openid: true,
				order_member_headimg: true,
				order_info: true,
				order_goods_cnt: true,
				create_uid: true,
			})
			.get();

		if (!(orderRes && orderRes.data && orderRes.data.length == 1)) {
			uniCloud.logger.info(`订单[${order_id}]不存在`);
			response.msg = `订单[${order_id}]不存在`;
			return response;
		}
		const order = orderRes.data[0];

		let orderUpdate = {
			state: state,

			last_modify_time: nowdate,
			last_modify_uname: this.ctx.auth.userInfo.username,
			last_modify_uid: uid
		};

		const orderUpdateRes = await this.db.collection('usemall-integral-order')
			.doc(order._id)
			.update(orderUpdate);

		if (orderUpdateRes && orderUpdateRes.updated == 1) {
			const order_log = {
				order_id: order.order_id,
				log_type: '已收货',
				current_state: state,
				prev_state: '待收货',
				ip: this.ctx.context.CLIENTIP,
				is_delete: 0,
				create_uid: uid,
				create_uname: this.ctx.auth.userInfo.username,
				create_time: nowdate
			};
			await this.db.collection('usemall-order-log').add(order_log);
		}

		response.datas = orderUpdateRes;

		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 查看订单物流
	async orderExpress() {
		let response = {
			code: 1,
			msg: '物流轨迹查询失败'
		};
	
		const {
			order_id
		} = this.ctx.data;
	
		if (!order_id) {
			response.msg = '订单号不存在';
			return response;
		}
	
		// 查询订单数据
		const orderRes = await this.db.collection('usemall-integral-order').where({
			order_id
		}).field({
			order_id: true,
			order_express: true,
			order_express_no: true,
			order_express_com: true,
			order_consignee_tel: true,
			order_express_datas: true
		}).get();
	
		if (!orderRes || orderRes.data.length !== 1) {
			response.msg = '订单不存在';
			return response;
		}
	
		const order = orderRes.data[0];
	
		// 存在有数据直接返回 express datas
		if (order.order_express_datas) {
			response.code = 0;
			response.msg = '物流轨迹查询成功';
			response.datas = order.order_express_datas;
			response.datas.company = order.order_express_com;
	
			return response;
		}
	
		if (!order.order_express_no) {
			response.msg = '快递单号不存在';
	
			return response;
		}
	
		// 调用快递100 实时快递查询接口
		const kd100Res = await this.service.express.kd100Query({
			"com": order.order_express_com || this.service.express.getKd100Com(order.order_express),
			"num": order.order_express_no,
			"phone": order.order_consignee_tel
		});
	
		response.datas = kd100Res;
		response.datas.company = order.order_express_com;
		response.msg = response.datas.message;
	
		if (response.datas && response.datas.message == "ok") {
			response.code = 0;
	
			/**
			 * 快递单状态
			 0 在途 快件处于运输过程中
			 1 揽收 快件已由快递公司揽收
			 2 疑难 快递100无法解析的状态，或者是需要人工介入的状态， 比方说收件人电话错误。
			 3 签收 正常签收
			 4 退签 货物退回发货人并签收
			 5 派件 货物正在进行派件
			 6 退回 货物正处于返回发货人的途中
			 7 转投 货物转给其他快递公司邮寄
			 10 待清关 货物等待清关
			 11 清关中 货物正在清关流程中
			 12 已清关 货物已完成清关流程
			 13 清关异常 货物在清关过程中出现异常
			 14 拒签 收件人明确拒收
			 */
			if (['3', '4', '14'].includes(response.datas.state)) {
				// 签收 退签 拒签
				// 写入订单物流轨迹数据
				await this.db.collection('usemall-integral-order').doc(order._id).update({
					order_express_datas: response.datas
				});
			}
		}
	
		return response;
	}

	// 刷新奖品池
	async refreshPrizePool() {
		let response = {
			code: 1
		};

		// 清理已有抽奖池数据
		const removeRes = await this.db.collection('usemall-lottery-pool').where({
			_id: this.db.command.exists(true)
		}).remove();

		// 查询抽奖配置表
		const lotteryParameterRes = await this.db.collection('usemall-lottery-parameter')
			.limit(1)
			.get();

		const [lotteryParameter] = lotteryParameterRes.data;

		// 抽奖功能未启用
		if (lotteryParameter.state === 0) {
			response.msg = '抽奖功能未启用';
			return response;
		}

		const prizes = lotteryParameter.prizes || [];
		// 抽奖功能未启用
		if (!prizes.length) {
			response.msg = '奖品未配置';
			return response;
		}

		const nowdate = Date.now();
		const nowtime = this.service.utils.toDateUTC8(new Date());
		const yymmdd = `${nowtime.getFullYear()}-${nowtime.getMonth() + 1}-${nowtime.getDate()}`;

		let idx = 0;
		const prizePool = [];
		// 按每项奖品权重生成奖品池
		for (var i = 0; i < prizes.length; i++) {
			const prize = prizes[i];

			for (var j = 0; j < prize.weight; j++) {
				idx++;
				prizePool.push({
					lottery_id: prize.id,
					idx: idx,
					yymmdd: yymmdd,
					state: 0,
					create_time: nowdate,
					create_uid: '',
					create_uname: 'job-day'
				});
			}
		}

		const count = prizePool.length;
		if (!count) {
			response.msg = '奖品权重未配置';
			return response;
		}

		const res = await this.db.collection('usemall-lottery-pool').add(prizePool);
		
		response.code = 0;
		response.msg = `已生成抽奖池×${res.ids.length}`;
		return response;
	}
	
	// 商品分类删除
	async classifyRemove() {
		let response = {
			code: 1,
			msg: '',
			datas: null
		};
	
		let {
			id
		} = this.ctx.data;
	
		try {
			const integralGoodsRes = await this.db.collection('usemall-integral-goods').where({
				cids: id
			}).get();
	
			if (!integralGoodsRes.data.length) {
				await this.db.collection('usemall-integral-category').doc(id).remove();
				response.msg = '操作成功';
				response.code = 0;
			} else {
				response.msg = '此分类存在商品，不可删除';
				response.code = 100;
			}
		}catch(err){
			response.msg = err.message;
			response.code = 500;
		}
	
		return response;
	}
}
